package com.example.onlinemusic.controller;

import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.service.LoveMusicService;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/loveMusic")
@RestController
public class LoveMusicController {

    @Autowired
    private LoveMusicService loveMusicService;

    /**
     * 收藏音乐
     * @param musicId
     * @param request
     * @return
     */
    @RequestMapping("/addLoveMusic")
    public ResponseBodyMessage<Boolean> addLoveMusic(@RequestParam int musicId, HttpServletRequest request) {
        User user = (User)request.getSession().getAttribute(Constant.USERINFO_SESSION_KEY);
        // 收藏音乐逻辑
        Boolean result = loveMusicService.addLoveMusic(user.getId(), musicId);
        if (!result) {
            return new ResponseBodyMessage<>(-1, "收藏失败，当前音乐已经收藏了！", false);
        }
        return new ResponseBodyMessage<>(0, "收藏成功！", true);
    }


    /**
     * 取消收藏的音乐
     * @param musicId
     * @param request
     * @return
     */
    @RequestMapping("/cancelLoveMusic")
    public ResponseBodyMessage<Boolean> cancelLoveMusic(@RequestParam int musicId, HttpServletRequest request) {
        User user = (User)request.getSession().getAttribute(Constant.USERINFO_SESSION_KEY);
        Boolean result = loveMusicService.cancelLoveMusic(user.getId(), musicId);
        if (!result) {
            return new ResponseBodyMessage<>(-1, "取消收藏失败，请检查网络！", false);
        }
        return new ResponseBodyMessage<>(0, "取消收藏成功！", true);
    }


    /**
     * 根据音乐名来查询当前用户收藏过的音乐 不传参则查询所有
     * @param title
     * @param request
     * @return
     */
    @RequestMapping("/getLoveMusic")
    public ResponseBodyMessage<List<Music>> getLoveMusic(@RequestParam(required = false) String title, HttpServletRequest request) {
        User user = (User)request.getSession().getAttribute(Constant.USERINFO_SESSION_KEY);
        List<Music> allLoveMusics = null;
        if (title == null) {
            allLoveMusics = loveMusicService.findAllLoveMusic(user.getId());
        } else {
            allLoveMusics = loveMusicService.findLoveMusicByTitleAndUID(user.getId(), title);
        }
        return new ResponseBodyMessage<>(0, "查询收藏的音乐成功！", allLoveMusics);
    }
}
